package com.qfedu.dao.impl;

import com.qfedu.dao.CartDao;
import com.qfedu.pojo.Cart;
import com.qfedu.utils.DataSourceUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * 创建者: QF-SUN
 * 创建时间: 2023/4/4 15:08
 * 描述:
 */
public class CartDaoImpl implements CartDao {

    QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource());

    @Override
    public Cart findCart(int uid, String goodsId) {
        String sql = "select * from tb_cart where id = ? and pid = ?";
        try {
            Cart cart = qr.query(sql, new BeanHandler<>(Cart.class), uid, goodsId);
            return cart;
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("查询购物车失败!!");
        }


        return null;
    }

    @Override
    public void insert(Cart cart) {
        String sql = "INSERT INTO `tb_cart`(`id`,`pid`,`Num`,`money`)VALUES(?,?,?,?)";
        try {
            qr.update(sql,  cart.getId(), cart.getPid(), cart.getNum(), cart.getMoney());
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("新增购物车失败!!");
        }
    }

    @Override
    public void update(Cart cart) {
        String sql = "UPDATE `tb_cart` SET `Num` = ?, `money` = ? WHERE `id` = ? AND `pid` = ?";
        try {
            qr.update(sql, cart.getNum(), cart.getMoney(), cart.getId(), cart.getPid());
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("修改购物车失败!!");
        }
    }

    @Override
    public List<Cart> findCartByUId(int uid) {
        String sql = "select * from tb_cart where id = ? ";
        try {
            List<Cart> carts = qr.query(sql, new BeanListHandler<>(Cart.class), uid);
            return carts;
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("查询购物车失败!!");
        }
        return null;
    }

    @Override
    public void deleteCart(int uid, String goodsId) {
        String sql = "delete from tb_cart where id = ? and pid = ?";
        try {
            qr.update(sql, uid, goodsId);
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("删除购物车失败!!");
        }
    }

    @Override
    public void clearCart(int id) {
        String sql = "delete from tb_cart where id = ?";
        try {
            qr.update(sql, id);
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("删除购物车失败!!");
        }
    }
}
